package com.websocket.filter;

import com.websocket.util.Contains;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by simon on 5/21/17.
 */
@WebFilter(filterName = "LoggerFilter", urlPatterns = "/*", initParams = {
        @WebInitParam(name = "author", value = "simon")
})
public class LoggerFilter implements Filter {
    private static Logger logger = LoggerFactory.getLogger(LoggerFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("------------------------------init----------------------------------");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        long startTime = System.currentTimeMillis();

        HttpServletRequest req = (HttpServletRequest) servletRequest;

        HttpSession session = req.getSession();
        if (session != null) {
            String sessionId = session.getId();
            // for log4j
            ThreadContext.put(Contains.X_SESSION_ID, sessionId);
        }

        // for log4j
        ThreadContext.put(Contains.X_UUID, UUID.randomUUID().toString());

        HttpServletRequest h = (HttpServletRequest) servletRequest;
        String requestURI = h.getRequestURI();
        if (h.getQueryString() != null) {
            requestURI += "?" + h.getQueryString();
        }
        logger.info("> {} {}", h.getMethod(), requestURI);

        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        logger.info("< Response, time-task: {} ms", (System.currentTimeMillis() - startTime));

        ThreadContext.clearAll();
    }

    @Override
    public void destroy() {
        logger.info("------------------------------destroy----------------------------------");
    }
}
